/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.result;

import java.io.*;
import java.net.*;

public class ResultSocket extends Thread {
    private Socket sock;

    public boolean done = false;

    public int status = 0;

    private ResultServer server = null;

    private int queryID = -1;

    public ResultSocket(Socket socket, ResultServer server) {
        sock = socket;
        this.server = server;
    }

    public void run() {
        //Socket sock = null;
        try {
            DataInputStream dis = new DataInputStream(sock.getInputStream());
            DataOutputStream dos = new DataOutputStream(sock.getOutputStream());

            queryID = dis.readInt();
            dis.readInt(); // Read the 'flag' value, not currently used

            ResultMarshall rm = this.server.getResultMarshall(queryID);
            if (rm == null) {
                System.err.println("Failed to locate result marshall for requested query (" + queryID + ").");
                return;
            }

            int type = -1;
            int sensor = -1;
            int len = -1;
            byte[] bytes = null;
            int bytesRead = 0;
            int val = 0;
            int count = 0;
            long startTS = System.currentTimeMillis();
            if (sock.isConnected()) {
                while (val == 0) {
                    try {
                        try {
                            type = dis.readInt();
                            if (type == -100) {
                                //System.out.println("------------DONE------------");
                                break;
                            } else if (type == -1)
                                break;
                            sensor = dis.readInt();
                            len = dis.readInt();
                            if (len == -1)
                                break;
                        } catch (EOFException eofe) {
                            //eofe.printStackTrace();
                            type = -1;
                            len = -1;
                            val = -1;
                        }
                        if ((type != -1) && (len != -1)) {
                            bytes = new byte[len];

                            bytesRead = 0;
                            while (bytesRead < len)
                                bytesRead += dis.read(bytes, bytesRead, len - bytesRead);

                            val = -1;

                            while (val == -1) {
                                if (type > 0) {
                                    val = rm.addRecord(new Record(type, sensor, new String(bytes)));
                                    if (val == 0)
                                        count++;
                                } else
                                    val = -1;
                                //val =
                                // rm.addRecord("12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
                                // type);
                                if (val != 0) {
                                    if (val == -1) {
                                        //System.out.println("ResultSocket:
                                        // tried to add record but failed,
                                        // sleeping...");
                                        Thread.sleep(5);
                                    } else {
                                        System.out.println("ResultSocket: tried to add record but failed exiting...");
                                    }
                                }
                                //System.out.println("ResultSocket: here I am
                                // ");
                            }
                        }
                    }
                    //resultOut.writeBytes(line + "\n");
                    catch (Exception e) {
                        e.printStackTrace();
                        dis.close();
                        sock.close();
                        //ss.close();
                        done = true;
                        status = -1;
                        //if (flag == NetForSE.RESULT_SERVER_FLAG_DONE)
                        rm.removeProducer();
                        return;
                    }

                }
            }
            long stopTS = System.currentTimeMillis();
            System.out.print("ResultSocket: processed " + count + " records in " + (stopTS - startTS) / 1000
                    + " seconds, ");
            if ((stopTS - startTS) / 1000 > 0)
                System.out.println(count / ((stopTS - startTS) / 1000) + " rps");
            else
                System.out.println();
            int expected = 0;
            try {
                expected = dis.readInt();
                rm.addExpected(expected);
                dos.writeInt(-100);
            } catch (Exception E) {
                //E.printStackTrace();
            }
            rm.removeProducer();

            dis.close();
            sock.close();
            done = true;
        } catch (Exception e) {
            done = true;
            status = -2;
            e.printStackTrace();
            try {
                sock.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
                status = -3;
            }
        }
    }

}